package com.gr.catanddog_web.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@WebFilter("/upload/*")
public class FileFilter implements Filter {
    @Value("${file.upload.url}")
    private String FILE_PATH;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String uri = servletRequest.getServletContext().getContextPath()+((HttpServletRequest)servletRequest).getServletPath();
        List<String> str = new ArrayList<>();
        str = List.of(uri.split("/", 8));
        if(uri.contains("upload")) {
            String filePath = FILE_PATH + uri.replace("/upload/", "/");
            File file = new File(filePath);
            FileInputStream fin = new FileInputStream(file);
            IOUtils.copy(fin, servletResponse.getOutputStream());
            fin.close();
        }else filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
    }
}
